<template>
  <Card>
    <Row :gutter="8" type="flex" class="ivu-mb-8">
      <!-- 张成成：时间段选择范围最多为一年以弹框形式提醒 -->
      <Col
        ><DatePicker
          v-model="params.time"
          type="daterange"
          :clearable="false"
          placeholder="请选择时间"
          v-width="200"
          @on-change="askData"
        ></DatePicker
      ></Col>
      <Col>
        <Select
          v-model="params.net_config_id"
          v-width="200"
          placeholder="请选择营销中心"
          @on-change="askDataConditions"
          clearable
        >
          <Option
            v-for="item in configList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </Col>
      <Col>
        <!-- <TreeSelect v-model="params.source_channel_id" :data="channelList" placeholder="选择渠道" v-width="200" @on-change="askData"/> -->
        <Select
          v-model="params.source_channel_id"
          multiple
          placeholder="选择渠道"
          clearable
          v-width="200"
          @on-change="askDataCondition"
        >
          <Option
            v-for="item in channelList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </Col>
      <Col><Button type="primary" @click="exportData">导出</Button></Col>
    </Row>
    <Table
      row-key="source_channel_id"
      :indent-size="0"
      :load-data="handleLoadData"
      :update-show-children="true"
      :columns="columns"
      :data="data"
      :loading="loading"
    >
      <template slot-scope="{ row }" slot="conunt">
        <span v-if="row.source_channel_id == 0">{{ row.yx_diff }}</span>
        <a v-else @click="changeDetail(row)">{{ row.yx_diff }}</a>
      </template>
    </Table>
    <Modal v-model="modalstatus" title="详情" width="1200" footer-hide>
      <Table :columns="modalcolumns" :data="modaldata"></Table>
      <div class="ivu-mt ivu-text-center">
        <Page
          show-total
          show-elevator
          show-sizer
          :total="total"
          :current.sync="params.page"
          :page-size="params.pageSize"
          :page-size-opts="pageOpts"
          @on-change="changepage"
          @on-page-size-change="changepageSize"
        ></Page>
      </div>
    </Modal>
  </Card>
</template>

<script>
import {
  projectCondition,
  marketingconsumeconsumereport,
  yxchangeDiff,
  netreportprojectcondition,
} from "@/api/hqapi/networkMarketing.js";
import * as XLSX from "xlsx";
export default {
  name: "marketingReport",

  data() {
    return {
      params: { time: [], source_channel_id: [], net_config_id: "" },
      columns: [
        {
          title: "渠道",
          key: "source_name",
          fixed: "left",
          tree: true,
          minWidth: 200,
        },
        { title: "消费金额", key: "all_consume", minWidth: 150 },
        { title: "基建金额", key: "all_construct_consume", minWidth: 150 },
        { title: "有效对话总数", key: "yxdh_num", width: 150 },
        { title: "留电", key: "ld_num", width: 100 },
        { title: "确诊白癜风对话", key: "qzbdf_num", width: 150 },
        { title: "有效到诊", key: "arrived_num", width: 100 },
        { title: "到诊率", key: "arrived_rate", width: 100 },
        { title: "有效对话成本", key: "yxdh_cost", width: 150 },
        { title: "确诊对话成本", key: "qzbdf_cost", width: 150 },
        { title: "到诊成本", key: "arrived_cost", minWidth: 150 },
        { title: "留电率", key: "ld_rate", width: 100 },
        { title: "有效转化", key: "yx_change", width: 100 },
        { title: "变动数据", slot: "conunt", width: 100, fixed: "right" },
      ],
      centerList: [],
      allData: {},
      allDatas: {},
      dataHeader: [],
      dataHeaders: [],
      dataData: [],
      data: [],
      loading: false,
      channelList: [],
      modalcolumns: [
        { title: "访问姓名", key: "name", minWidth: 150 },
        { title: "对话时间", key: "dialogue_time", minWidth: 180 },
        { title: "手机号", key: "mobile", minWidth: 150 },
        { title: "微信号", key: "wechat_num", minWidth: 150 },
        { title: "访问ID", key: "visitor_static_id", minWidth: 150 },
        { title: "IP", key: "ip", minWidth: 100 },
        { title: "渠道", key: "source_name", minWidth: 100 },
        { title: "原因", key: "reason", minWidth: 150 },
      ],
      modaldata: [],
      page: 1,
      pageSize: 10,
      total: 0,
      pageOpts: [10, 20, 50, 100],
      modalstatus: false,
      source_channel_id: "",
      configList: [],
    };
  },

  mounted() {
    let time = [
      this.$Date()
        .startOf("month")
        .format("YYYY-MM-DD"),
      this.$Date().format("YYYY-MM-DD"),
    ];
    if (time[0] == time[1]) {
      this.params.time = [
        this.$Date()
          .startOf("month")
          .format("YYYY-MM-DD"),
        this.$Date().format("YYYY-MM-DD"),
      ];
    } else {
      // console.log(this.$Date(new Date()-3600 * 1000 * 24).format('YYYY-MM-DD'),'1')
      this.params.time = [
        this.$Date()
          .startOf("month")
          .format("YYYY-MM-DD"),
        this.$Date(new Date() - 3600 * 1000 * 24).format("YYYY-MM-DD"),
      ];
    }
    this.initial();
  },

  methods: {
    initial() {
      this.askData();
      // projectCondition().then(res => {
      //     this.channelList = res.channel;
      // });
      this.askDataCondition();
    },
    askDataConditions() {
      this.params.source_channel_id = "";
      this.askDataCondition();
    },
    askDataCondition() {
      let params = {
        source_channel_id: this.params.source_channel_id,
        net_config_id: this.params.net_config_id,
      };
      projectCondition(params).then((res) => {
        this.configList = res.config;
        this.channelList = res.channel;
        this.askData();
      });
    },
    askData() {
      if (
        this.$Date(this.params.time[1]).diff(
          this.$Date(this.params.time[0]),
          "years"
        ) > 0
      ) {
        this.$Message.error("时间段选择请勿超过一年");
      } else {
        this.loading = true;
        let params = {
          start_time: this.params.time[0],
          end_time: this.params.time[1],
          source_channel_id: this.params.source_channel_id
            ? this.params.source_channel_id.join(",")
            : "",
          net_config_id: this.params.net_config_id,
        };
        marketingconsumeconsumereport(params).then((res) => {
          this.data = [];
          this.dataHeader = [];
          this.dataHeaders = [];
          this.dataData = res.list;
          res.list.forEach((item) => {
            if (item.source_name !== "合计") {
              this.dataHeader.push(item.source_name);
            }
            this.allData[item.source_channel_id] = item.children;
            this.allDatas[item.source_name] = item.children;
            this.dataHeaders[item.source_name] = {
              source_name: "总计",
              all_consume: item.all_consume,
              all_construct_consume: item.all_construct_consume,
              yxdh_num: item.yxdh_num,
              ld_num: item.ld_num,
              qzbdf_num: item.qzbdf_num,
              arrived_num: item.arrived_num,
              arrived_rate: item.arrived_rate,
              yxdh_cost: item.yxdh_cost,
              qzbdf_cost: item.qzbdf_cost,
              arrived_cost: item.arrived_cost,
              ld_rate: item.ld_rate,
              yx_change: item.yx_change,
              yx_diff: item.yx_diff,
            };
            if (item.children) {
              this.data.push({
                _loading: false,
                all_consume: item.all_consume,
                all_construct_consume: item.all_construct_consume,
                arrived_cost: item.arrived_cost,
                arrived_num: item.arrived_num,
                arrived_rate: item.arrived_rate,
                first_bdf_num: item.first_bdf_num,
                ld_num: item.ld_num,
                children: [],
                ld_rate: item.ld_rate,
                qzbdf_cost: item.qzbdf_cost,
                qzbdf_num: item.qzbdf_num,
                second_bdf_num: item.second_bdf_num,
                source_channel_id: item.source_channel_id,
                source_name: item.source_name,
                yxdh_cost: item.yxdh_cost,
                yxdh_num: item.yxdh_num,
                yx_change: item.yx_change,
                yx_diff: item.yx_diff,
              });
            } else {
              this.data.push({
                all_consume: item.all_consume,
                all_construct_consume: item.all_construct_consume,
                arrived_cost: item.arrived_cost,
                arrived_num: item.arrived_num,
                arrived_rate: item.arrived_rate,
                first_bdf_num: item.first_bdf_num,
                ld_num: item.ld_num,
                ld_rate: item.ld_rate,
                qzbdf_cost: item.qzbdf_cost,
                qzbdf_num: item.qzbdf_num,
                second_bdf_num: item.second_bdf_num,
                source_channel_id: item.source_channel_id,
                source_name: item.source_name,
                yxdh_cost: item.yxdh_cost,
                yxdh_num: item.yxdh_num,
                yx_change: item.yx_change,
                yx_diff: item.yx_diff,
              });
            }
          });
          this.loading = false;
        });
      }
    },
    // 获取变动数据详情
    changeDetail(row) {
      if (row.source_channel_id == 0) {
        this.modalstatus = false;
      } else {
        this.source_channel_id = row.source_channel_id;
        this.getDetails();
        this.modalstatus = true;
      }
    },
    getDetails() {
      const params = {
        start_time: this.$Date(this.params.time[0]).format("YYYY-MM-DD"),
        end_time: this.$Date(this.params.time[1]).format("YYYY-MM-DD"),
        source_channel_id: this.source_channel_id,
        page: this.page,
        pageSize: this.pageSize,
      };
      yxchangeDiff(params).then((res) => {
        this.modaldata = res.list;
        this.total = res.total;
      });
    },
    changepage(index) {
      this.page = index;
      this.getDetails();
    },
    changepageSize(e) {
      this.pageSize = e;
      this.getDetails();
    },
    handleLoadData(item, callback) {
      item._loading = true;
      setTimeout(() => {
        const data = this.allData[item.source_channel_id];
        callback(data);
      });
    },
    exportData() {
      // if (this.datas.length > 0) {
      //     this.$refs.tables.exportCsv({
      //         filename: '营销报表'
      //     });
      // } else {
      //     this.$Message.error('暂无数据');
      // }
      const wb = XLSX.utils.book_new();
      console.log(this.dataData, "this.dataData");
      let data = this.dataData.map((item) => {
        return {
          渠道: item.source_name,
          消费金额: item.all_consume,
          基建金额: item.all_construct_consume,
          有效对话总数: item.yxdh_num,
          留电: item.ld_num,
          确诊白癜风对话: item.qzbdf_num,
          有效到诊: item.arrived_num,
          到诊率: item.arrived_rate,
          有效对话成本: item.yxdh_cost,
          确诊对话成本: item.qzbdf_cost,
          到诊成本: item.arrived_cost,
          留电率: item.ld_rate,
          有效转化: item.yx_change,
          变动数据: item.yx_diff,
        };
      });
      let datas = XLSX.utils.json_to_sheet(data);
      XLSX.utils.book_append_sheet(wb, datas, "总表");
      this.dataHeader.forEach((events) => {
        let data1 = this.allDatas[events].map((item) => {
          return {
            渠道: item.source_name,
            消费金额: item.all_consume,
            基建金额: item.all_construct_consume,
            有效对话总数: item.yxdh_num,
            留电: item.ld_num,
            确诊白癜风对话: item.qzbdf_num,
            有效到诊: item.arrived_num,
            到诊率: item.arrived_rate,
            有效对话成本: item.yxdh_cost,
            确诊对话成本: item.qzbdf_cost,
            到诊成本: item.arrived_cost,
            留电率: item.ld_rate,
            有效转化: item.yx_change,
            变动数据: item.yx_diff,
          };
        });
        data1.push({
          渠道: this.dataHeaders[events].source_name,
          消费金额: this.dataHeaders[events].all_consume,
          基建金额: this.dataHeaders[events].all_construct_consume,
          有效对话总数: this.dataHeaders[events].yxdh_num,
          留电: this.dataHeaders[events].ld_num,
          确诊白癜风对话: this.dataHeaders[events].qzbdf_num,
          有效到诊: this.dataHeaders[events].arrived_num,
          到诊率: this.dataHeaders[events].arrived_rate,
          有效对话成本: this.dataHeaders[events].yxdh_cost,
          确诊对话成本: this.dataHeaders[events].qzbdf_cost,
          到诊成本: this.dataHeaders[events].arrived_cost,
          留电率: this.dataHeaders[events].ld_rate,
          有效转化: this.dataHeaders[events].yx_change,
          变动数据: this.dataHeaders[events].yx_diff,
        });
        let data2 = XLSX.utils.json_to_sheet(data1);
        XLSX.utils.book_append_sheet(wb, data2, events);
      });
      console.log(wb, "www");
      const workbookBlob = this.workbook2blob(wb);
      this.openDownloadDialog(workbookBlob, "营销报表.xlsx");
    },
    // 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
    workbook2blob(workbook) {
      // 生成excel的配置项
      var wopts = {
        // 要生成的文件类型
        bookType: "xlsx",
        // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        bookSST: false,
        // 二进制类型
        type: "binary",
      };
      var wbout = XLSX.write(workbook, wopts);
      var blob = new Blob([this.s2ab(wbout)], {
        type: "application/octet-stream",
      });
      return blob;
    },

    // 将字符串转ArrayBuffer
    s2ab(s) {
      var buf = new ArrayBuffer(s.length);
      var view = new Uint8Array(buf);
      for (var i = 0; i != s.length; ++i) {
        view[i] = s.charCodeAt(i) & 0xff;
      }
      return buf;
    },

    // 将blob对象创建bloburl，然后用a标签实现弹出下载框
    openDownloadDialog(blob, fileName) {
      if (typeof blob === "object" && blob instanceof Blob) {
        blob = URL.createObjectURL(blob); // 创建blob地址
      }
      var aLink = document.createElement("a");
      aLink.href = blob;
      // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，有时候 file:///模式下不会生效
      aLink.download = fileName || "";
      var event;
      if (window.MouseEvent) event = new MouseEvent("click");
      //   移动端
      else {
        event = document.createEvent("MouseEvents");
        event.initMouseEvent(
          "click",
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
      }
      aLink.dispatchEvent(event);
      URL.revokeObjectURL(blob);
    },
  },
};
</script>
